package com.chihiro.kiosk_model

import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import android.app.Activity
import android.os.Binder
import android.os.IBinder
import android.util.Log
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.EventChannel

private const val methodChannelName = "com.chihiro.kiosk_model"

/** KioskModelPlugin */
class KioskModelPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {
    private lateinit var channel: MethodChannel
    private lateinit var eventChannel: EventChannel
    private var activity: Activity? = null
    private var androidDevicePolicyManager: AndroidDevicePolicyManager? = null

    companion object {
        private var TAG = KioskModelPlugin::class.java.simpleName
    }

    override fun onAttachedToEngine(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, methodChannelName)
        channel.setMethodCallHandler(this)

    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "startKioskMode" -> startKioskMode(result)
            "stopKioskMode" -> stopKioskMode(result)
            "owner" -> ownerApp(result)
            "hideNavigationBar" -> statusBarDisable(result,
                (call.arguments as Map<*, *>)["hideNavigationBar"] as Boolean)
            else -> result.notImplemented()
        }
    }

    private fun ownerApp(result: MethodChannel.Result) {
        Log.i(TAG, "ownerApp${androidDevicePolicyManager?.isDeviceOwnerApp()}")
        result.success(androidDevicePolicyManager?.isDeviceOwnerApp() ?: false)
    }

    // 启动kiosk模式
    private fun startKioskMode(result: MethodChannel.Result) {
        try {
            androidDevicePolicyManager?.startLockTask()
            result.success(true)
        } catch (e: Exception) {
            result.success(false)
        }
    }

    // 停止kiosk模式
    private fun stopKioskMode(result: MethodChannel.Result) {
        try {
            androidDevicePolicyManager?.stopLockTask()
            result.success(true)
        } catch (e: Exception) {
            result.success(false)
        }
    }


    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
        eventChannel.setStreamHandler(null)
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.activity = binding.activity
        androidDevicePolicyManager = activity?.let {
            AndroidDevicePolicyManager(
                it,
                AndroidDeviceAdminReceiver.getComponentName(it)
            )
        }
    }

    override fun onDetachedFromActivityForConfigChanges() {}
    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        activity = binding.activity
        androidDevicePolicyManager = activity?.let {
            AndroidDevicePolicyManager(
                it,
                AndroidDeviceAdminReceiver.getComponentName(it)
            )
        }
    }

    override fun onDetachedFromActivity() {
        this.activity = null
    }

    private fun statusBarDisable(result: MethodChannel.Result,disable: Boolean) {
        Log.i(TAG, "statusBarDisable->disable:$disable")
        try {
            val DISABLE_NAVIGATION = 0x00200000 or 0x00400000 or 0x01000000
            //int DISABLE_NAVIGATION =  View.STATUS_BAR_DISABLE_HOME | View.STATUS_BAR_DISABLE_BACK | View.STATUS_BAR_DISABLE_RECENT;
            val DISABLE_NONE = 0x00000000
            //获得ServiceManager类
            val serviceManager = Class
                .forName("android.os.ServiceManager")

            //获得ServiceManager的getService方法
            val getService = serviceManager.getMethod("getService", String::class.java)

            //调用getService获取RemoteService
            val oRemoteService = getService.invoke(null, "statusbar")

            //获得IStatusBarService.Stub类
            val cStub = Class
                .forName("com.android.internal.statusbar.IStatusBarService\$Stub")
            //获得asInterface方法
            val asInterface = cStub.getMethod("asInterface", IBinder::class.java)
            //调用asInterface方法获取IStatusBarService对象
            val oIStatusBarService = asInterface.invoke(null, oRemoteService)
            //获得disable()方法
            val disableMethod = oIStatusBarService.javaClass.getMethod(
                "disable",
                Int::class.javaPrimitiveType,
                IBinder::class.java,
                String::class.java
            )
            //调用disable()方法
            if (disable) {
                disableMethod.invoke(
                    oIStatusBarService,
                    DISABLE_NAVIGATION,
                    Binder(),
                    activity?.packageName
                )
            } else {
                disableMethod.invoke(
                    oIStatusBarService,
                    DISABLE_NONE,
                    Binder(),
                    activity?.packageName
                )
            }
            result.success(true)
        } catch (e: Exception) {
            Log.e(TAG, e.toString(), e)
            result.success(false)
        }
    }
}